package com.tsystems.school.jabber.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

import com.tsystems.school.jabber.Message;
import com.tsystems.school.jabber.MessageType;


public class Sender implements Runnable{
  private InetAddress ip;
  private int port;
  private Message msg;
  
  public Sender(InetAddress ip, int port, Message msg){
    this.msg = msg;
    this.ip = ip;
    this.port = port;
  }

  @Override
  public void run() {
    // TODO Auto-generated method stub
    Socket s = null;
      try {
        s = new Socket(ip, port);
      } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      try {
        InputStream in = s.getInputStream();
        OutputStream out = s.getOutputStream();
        String st = msg.toJSON();
        st = st.length() + st;
        out.write(st.getBytes());
        String ss = null;
        byte[] cb = new byte[4000];
        while (in.read(cb) > 0){
          for (int i = 0; i< 4000; i++)
          System.out.println(((char)cb[i]));
        }
        
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      
     
  }
  
  public static void main(String [] args){
    Message m = new Message();
    m.setType(MessageType.LOGIN);
    m.putProperty("login", "UserXXX");
    m.putProperty("pass", "xxx");
    try {
      (new Sender(InetAddress.getByName("localhost"), 6666, m)).run();
    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
}
